import React, { useEffect, useRef, useState } from 'react'
import './Sport.css'

const Sport: React.FC = () => {
  
  // 计时器相关状态
  const [isRunning, setIsRunning] = useState(false)
  const [isPaused, setIsPaused] = useState(false)
  const [currentTime, setCurrentTime] = useState(0)
  const [distance, setDistance] = useState(0)
  const [speed, setSpeed] = useState(0)
  const intervalRef = useRef<number | null>(null)
  const lastPointRef = useRef<[number, number] | null>(null)
  const [showSummary, setShowSummary] = useState(false)
  const [showHistory, setShowHistory] = useState(false)
  const startEpochRef = useRef<number | null>(null)
  const pausedTotalRef = useRef(0)
  const pauseStartedRef = useRef<number | null>(null)
  type RunRecord = { id: string; ts: number; durationSec: number; km: number; avgKmh: number }
  // 天气/适宜度
  type WeatherNow = { temperature: number; windspeed: number; humidity: number; code: number }
  const [weather, setWeather] = useState<WeatherNow | null>(null)
  const [suitText, setSuitText] = useState<string>('正在获取天气...')
  const [weatherRefresh, setWeatherRefresh] = useState(0)
  const [userLoc, setUserLoc] = useState<{ lat: number; lng: number } | null>(null)
  const [city, setCity] = useState<string>('保定市')
  const [history, setHistory] = useState<RunRecord[]>(() => {
    try {
      const raw = localStorage.getItem('runHistory')
      return raw ? (JSON.parse(raw) as RunRecord[]) : []
    } catch {
      return []
    }
  })

  // 本周统计（借鉴常见跑步 App 的每周概览）
  const weekStats = (() => {
    try {
      const now = new Date()
      const day = now.getDay() || 7 // 将周日设为 7
      const weekStart = new Date(now)
      weekStart.setHours(0, 0, 0, 0)
      weekStart.setDate(now.getDate() - (day - 1)) // 周一作为开始
      let kmTotal = 0
      let durationSecTotal = 0
      let longestKm = 0
      let count = 0
      for (const r of history) {
        if (r.ts >= weekStart.getTime()) {
          kmTotal += r.km
          durationSecTotal += r.durationSec
          longestKm = Math.max(longestKm, r.km)
          count += 1
        }
      }
      const avgPaceMinPerKm = kmTotal > 0 ? (durationSecTotal / 60) / kmTotal : 0
      return {
        kmTotal: Number(kmTotal.toFixed(2)),
        durationSecTotal,
        longestKm: Number(longestKm.toFixed(2)),
        count,
        avgPaceMinPerKm: Number(avgPaceMinPerKm.toFixed(1)),
      }
    } catch {
      return { kmTotal: 0, durationSecTotal: 0, longestKm: 0, count: 0, avgPaceMinPerKm: 0 }
    }
  })()

  // 格式化时间显示
  const formatTime = (seconds: number): string => {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60
    
    if (hours > 0) {
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    }
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }

  // 计算两点间距离（米）
  const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
    const R = 6371000 // 地球半径（米）
    const dLat = (lat2 - lat1) * Math.PI / 180
    const dLon = (lon2 - lon1) * Math.PI / 180
    const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
              Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
              Math.sin(dLon/2) * Math.sin(dLon/2)
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
    return R * c
  }

  // 开始跑步
  const startRunning = () => {
    setIsRunning(true)
    setIsPaused(false)
    startEpochRef.current = Date.now()
    pausedTotalRef.current = 0
    pauseStartedRef.current = null
    setCurrentTime(0)
    setDistance(0)
    lastPointRef.current = null
    
    // 清除之前的定时器
    if (intervalRef.current !== null) {
      clearInterval(intervalRef.current)
    }
    
    // 开始计时
    intervalRef.current = window.setInterval(() => {
      if (startEpochRef.current !== null) {
        const elapsed = Math.floor((Date.now() - startEpochRef.current - pausedTotalRef.current) / 1000)
        setCurrentTime(elapsed)
        if (elapsed > 0) setSpeed(distance / elapsed)
      }
    }, 1000)
  }

  // 暂停跑步
  const pauseRunning = () => {
    setIsPaused(true)
    if (intervalRef.current !== null) {
      clearInterval(intervalRef.current)
      intervalRef.current = null
    }
    pauseStartedRef.current = Date.now()
  }

  // 恢复跑步
  const resumeRunning = () => {
    setIsPaused(false)
    if (pauseStartedRef.current !== null) {
      pausedTotalRef.current += Date.now() - pauseStartedRef.current
      pauseStartedRef.current = null
    }
    
    intervalRef.current = window.setInterval(() => {
      if (startEpochRef.current !== null) {
        const elapsed = Math.floor((Date.now() - startEpochRef.current - pausedTotalRef.current) / 1000)
        setCurrentTime(elapsed)
        if (elapsed > 0) setSpeed(distance / elapsed)
      }
    }, 1000)
  }

  // 结束跑步
  const stopRunning = () => {
    setIsRunning(false)
    setIsPaused(false)
    startEpochRef.current = null
    pausedTotalRef.current = 0
    pauseStartedRef.current = null
    if (intervalRef.current !== null) {
      clearInterval(intervalRef.current)
      intervalRef.current = null
    }
    // 保存记录
    const durationSec = currentTime
    const km = distance / 1000
    const avgKmh = durationSec > 0 ? (distance / durationSec) * 3.6 : 0
    const rec: RunRecord = { id: `${Date.now()}`, ts: Date.now(), durationSec, km: Number(km.toFixed(2)), avgKmh: Number(avgKmh.toFixed(1)) }
    setHistory((prev) => {
      const next = [rec, ...prev]
      try { localStorage.setItem('runHistory', JSON.stringify(next)) } catch {}
      return next
    })
    setShowSummary(true)
  }

  // GO按钮点击处理
  const handleGoClick = () => {
    if (!isRunning) {
      startRunning()
    } else if (isPaused) {
      resumeRunning()
    } else {
      pauseRunning()
    }
  }

  // 清理定时器
  useEffect(() => {
    return () => {
      if (intervalRef.current !== null) {
        clearInterval(intervalRef.current)
      }
    }
  }, [])

  // 天气：使用用户实时定位拉取 Open-Meteo 当前天气与适宜性
  useEffect(() => {
    const load = async () => {
      try {
        const lat = userLoc?.lat ?? defaultCenter[1]
        const lng = userLoc?.lng ?? defaultCenter[0]
        const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}&current=temperature_2m,relative_humidity_2m,wind_speed_10m,weather_code&timezone=auto`
        const res = await fetch(url)
        const data = await res.json()
        const cur = data?.current
        if (cur) {
          const w: WeatherNow = {
            temperature: cur.temperature_2m,
            windspeed: cur.wind_speed_10m,
            humidity: cur.relative_humidity_2m,
            code: cur.weather_code,
          }
          setWeather(w)
          const tempOk = w.temperature >= 8 && w.temperature <= 28
          const windOk = w.windspeed <= 8
          const humidOk = w.humidity >= 25 && w.humidity <= 85
          const codeBad = [95, 96, 99, 80, 81, 82, 61, 62, 63, 65, 66, 67, 71, 73, 75]
          const isBad = codeBad.includes(w.code)
          let text = '适宜跑步'
          if (!tempOk || !windOk || !humidOk) text = '一般，注意补给与配速'
          if (isBad) text = '不适宜，建议改为室内'
          setSuitText(text)
        } else {
          setSuitText('天气获取失败')
        }
      } catch {
        setSuitText('天气获取失败')
      }
    }
    load()
  }, [userLoc, weatherRefresh])

  // 反向地理编码：根据 userLoc 解析城市名
  useEffect(() => {
    const fetchCity = async () => {
      if (!userLoc) return
      try {
        const url = `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${userLoc.lat}&lon=${userLoc.lng}`
        const res = await fetch(url, { headers: { 'Accept-Language': 'zh-CN' } })
        const data = await res.json()
        const addr = data?.address || {}
        const name = addr.city || addr.town || addr.village || addr.county || addr.state || '未知位置'
        setCity(name)
      } catch {
        setCity('未知位置')
      }
    }
    fetchCity()
  }, [userLoc])

  return (
    <>
    <div className="sport-page">
      <div className="sport-header">
        <div className="title">
           户外跑步
        </div>
        <div className="actions">
          <button className="icon-btn" aria-label="history" title="历史跑步记录" onClick={() => setShowHistory(true)}>🏅</button>
        </div>
      </div>

      {/* 已按需求移除：模式选择按钮（户外跑步/行走/跳绳） */}

      <div className="map-card">
        {/* 天气适宜度 */}
        <div className="weather-tip">
          <div className={`weather-dot ${suitText.includes('不适宜') ? 'bad' : suitText.includes('一般') ? 'warn' : 'good'}`}></div>
          <div className="weather-text">
            {weather ? (
              <>
                <span className="w-city">{city}</span>
                <span className="w-strong"> · {suitText}</span>
                <span className="w-weak"> | {weather.temperature.toFixed(0)}°C · 风 {weather.windspeed.toFixed(1)} m/s · 湿度 {weather.humidity}%</span>
              </>
            ) : (
              <>
                <span className="w-city">{city}</span>
                <span className="w-weak"> · {suitText}</span>
              </>
            )}
          </div>
          <button className="weather-refresh" onClick={() => {
            setSuitText('正在获取天气...')
            setWeather(null)
            setWeatherRefresh((n) => n + 1)
          }}>↻</button>
        </div>
        <div className="map-view">
          <AMapRealtime 
            keyStr={import.meta.env.VITE_AMAP_KEY || "8467428f2c98b0ba34a6db6c3767f134"} 
            isRunning={isRunning}
            onLocationUpdate={(lat, lng) => {
              // 跑步中用于距离计算
              if (isRunning && !isPaused) {
                const previous = lastPointRef.current
                const current: [number, number] = [lng, lat]
                if (previous) {
                  const newDistance = calculateDistance(previous[1], previous[0], lat, lng)
                  setDistance(prevDistance => prevDistance + newDistance)
                }
                lastPointRef.current = current
              }
              // 始终记录定位用于天气
              setUserLoc({ lat, lng })
            }}
          />
          <AMapButtons />
        </div>
      </div>

      {/* 已按需求移除：Tabs（目标跑/自由跑/课程跑/自创） */}

      {/* 跑步时的计时器显示 */}
      {isRunning && (
        <div className="running-stats">
          <div className="stat-item">
            <div className="stat-value">{formatTime(currentTime)}</div>
            <div className="stat-label">时间</div>
          </div>
          <div className="stat-item">
            <div className="stat-value">{(distance / 1000).toFixed(2)}</div>
            <div className="stat-label">公里</div>
          </div>
          <div className="stat-item">
            <div className="stat-value">{speed > 0 ? (speed * 3.6).toFixed(1) : '0.0'}</div>
            <div className="stat-label">时速(km/h)</div>
          </div>
        </div>
      )}

      <div className="go-row">
        {!isRunning ? (
          <button 
            className="go-button"
            onClick={handleGoClick}
          >
            GO
          </button>
        ) : (
          <>
            <button 
              className={`go-button ${isPaused ? '' : 'paused'}`}
              onClick={handleGoClick}
            >
              <span className="go-icon">{isPaused ? '▶' : '⏸'}</span>
              <span className="go-text">{isPaused ? '继续' : '暂停'}</span>
            </button>
            <button 
              className="go-button running"
              onClick={stopRunning}
            >
              <span className="go-icon">■</span>
              <span className="go-text">结束</span>
            </button>
          </>
        )}
      </div>

      {/* 每周概览与快捷功能区域（填充底部空白） */}
      <div className="week-card">
        <div className="week-row">
          <div className="week-item">
            <div className="week-label">本周里程</div>
            <div className="week-value">{weekStats.kmTotal.toFixed(2)}<span className="unit"> km</span></div>
          </div>
          <div className="week-item">
            <div className="week-label">本周次数</div>
            <div className="week-value">{weekStats.count}<span className="unit"> 次</span></div>
          </div>
          <div className="week-item">
            <div className="week-label">平均配速</div>
            <div className="week-value">{weekStats.avgPaceMinPerKm > 0 ? weekStats.avgPaceMinPerKm : 0}<span className="unit"> 分/公里</span></div>
          </div>
        </div>
        <div className="week-sub">
          最长单次 {weekStats.longestKm.toFixed(2)} km · 累计时间 {formatTime(weekStats.durationSecTotal)}
        </div>
      </div>

      {/* 按需求移除：底部四个快捷按钮（历史/目标/热身/音乐） */}
    </div>
    {showSummary && (
      <div className="summary-mask" onClick={() => setShowSummary(false)}>
        <div className="summary-sheet" onClick={(e) => e.stopPropagation()}>
          <div className="summary-title">本次运动</div>
          <div className="running-stats">
            <div className="stat-item">
              <div className="stat-value">{formatTime(currentTime)}</div>
              <div className="stat-label">时间</div>
            </div>
            <div className="stat-item">
              <div className="stat-value">{(distance / 1000).toFixed(2)}</div>
              <div className="stat-label">公里</div>
            </div>
            <div className="stat-item">
              <div className="stat-value">{speed > 0 ? (speed * 3.6).toFixed(1) : '0.0'}</div>
              <div className="stat-label">时速(km/h)</div>
            </div>
          </div>
          <button className="summary-close" onClick={() => { setShowSummary(false); setShowHistory(true) }}>完成</button>
        </div>
      </div>
    )}
    {showHistory && (
      <div className="side-mask" onClick={() => setShowHistory(false)}>
        <div className="side-panel" onClick={(e) => e.stopPropagation()}>
          <div className="side-header">
            <div className="side-title">历史跑步记录</div>
            <button className="side-close" onClick={() => setShowHistory(false)}>×</button>
          </div>
          <div className="side-content">
            {history.length === 0 ? (
              <div className="empty">暂无记录</div>
            ) : (
              <ul className="history-list">
                {history.map((h) => (
                  <li key={h.id} className="history-item">
                    <div className="history-main">
                      <div className="history-km">{h.km.toFixed(2)} km</div>
                      <div className="history-time">{formatTime(h.durationSec)}</div>
                    </div>
                    <div className="history-sub">
                      <span>{new Date(h.ts).toLocaleString()}</span>
                      <span>平均 {h.avgKmh.toFixed(1)} km/h</span>
                    </div>
                  </li>
                ))}
              </ul>
            )}
          </div>
        </div>
      </div>
    )}
    </>
  )
}

export default Sport


// ======= AMap 实时轨迹（使用你的 Key） =======
declare global { interface Window { AMap: any } }

// 模块级距离计算，供地图与页面共享
function calcDistance(lat1: number, lon1: number, lat2: number, lon2: number): number {
  const R = 6371000
  const dLat = (lat2 - lat1) * Math.PI / 180
  const dLon = (lon2 - lon1) * Math.PI / 180
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
            Math.sin(dLon/2) * Math.sin(dLon/2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
  return R * c
}

const amapStore = {
  map: null as any,
  polyline: null as any,
  marker: null as any,
  watchId: null as number | null,
  buildings: null as any,
  accuracyCircle: null as any,
}

function loadAMapOnce(key: string): Promise<any> {
  return new Promise((resolve, reject) => {
    if (window.AMap) return resolve(window.AMap)
    
    // 检查API Key是否有效
    if (!key || key === 'your_amap_key_here') {
      reject(new Error('请配置有效的高德地图API Key'))
      return
    }
    
    const script = document.createElement('script')
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${key}`
    script.async = true
    script.onload = () => {
      if (window.AMap) {
        resolve(window.AMap)
      } else {
        reject(new Error('AMap SDK 加载失败'))
      }
    }
    script.onerror = (error) => {
      console.error('地图API加载失败:', error)
      reject(new Error('AMap SDK 加载失败，请检查网络连接和API Key'))
    }
    document.head.appendChild(script)
  })
}

const defaultCenter: [number, number] = [115.488980, 38.814759] // 河北科技学院图书馆（保定理工学院东院右边）

const AMapRealtime: React.FC<{ 
  keyStr: string
  isRunning?: boolean
  onLocationUpdate?: (lat: number, lng: number) => void
}> = ({ keyStr, onLocationUpdate }) => {
  const containerRef = useRef<HTMLDivElement | null>(null)
  const [mapError, setMapError] = useState<string | null>(null)

  useEffect(() => {
    let disposed = false
    if (!containerRef.current) return

    setMapError(null) // 重置错误状态
    loadAMapOnce(keyStr)
      .then((AMap: any) => {
        if (disposed) return
        const map = new AMap.Map(containerRef.current as HTMLDivElement, {
          viewMode: '3D',
          zoom: 15,
          center: defaultCenter,
          dragEnable: true,
          zoomEnable: true,
        })
        amapStore.map = map

        // 增强 3D 可视化：开启楼块与俯仰
        try {
          // 开启俯仰角与旋转交互
          map.setStatus({ pitchEnable: true, rotateEnable: true })
          map.setPitch(45)
          map.setRotation(0)
          // 添加默认楼块图层（若可用）
          if (AMap.buildings) {
            const buildings = new AMap.Buildings()
            map.add(buildings)
            amapStore.buildings = buildings
          }
        } catch {}

        const polyline = new AMap.Polyline({
          path: [],
          strokeColor: '#10b981',
          strokeWeight: 6,
          strokeOpacity: 1,
          showDir: true,
        })
        map.add(polyline)
        amapStore.polyline = polyline

        const marker = new AMap.CircleMarker({
          center: defaultCenter,
          radius: 6,
          strokeColor: '#fff',
          strokeWeight: 2,
          fillColor: '#10b981',
          fillOpacity: 1,
        })
        map.add(marker)
        amapStore.marker = marker

        // 小工具：将 WGS84(GPS) 转 GCJ02(高德)
        const convertGpsToGcj = (lng: number, lat: number): Promise<[number, number]> => {
          return new Promise((resolve) => {
            try {
              AMap.convertFrom([lng, lat], 'gps', (status: string, result: any) => {
                if (status === 'complete' && result?.locations?.length) {
                  const loc = result.locations[0]
                  resolve([loc.lng, loc.lat])
                } else {
                  resolve([lng, lat])
                }
              })
            } catch {
              resolve([lng, lat])
            }
          })
        }

        if ('geolocation' in navigator) {
          // 先拿一次当前位置，立即居中（电脑/手机都适用）
          navigator.geolocation.getCurrentPosition(
            (pos) => {
              const { latitude, longitude, accuracy } = pos.coords
              convertGpsToGcj(longitude, latitude).then((gcj) => {
                const here: [number, number] = [gcj[0], gcj[1]]
                marker.setCenter(here)
                // 通知外层当前定位
                try { if (onLocationUpdate) onLocationUpdate(here[1], here[0]) } catch {}
                // 精度圆
                try {
                  if (!amapStore.accuracyCircle) {
                    amapStore.accuracyCircle = new AMap.Circle({
                      center: here,
                      radius: accuracy || 0,
                      fillOpacity: 0.08,
                      fillColor: '#10b981',
                      strokeColor: '#10b981',
                      strokeOpacity: 0.35,
                      strokeWeight: 1,
                    })
                    map.add(amapStore.accuracyCircle)
                  } else {
                    amapStore.accuracyCircle.setCenter(here)
                    if (accuracy) amapStore.accuracyCircle.setRadius(accuracy)
                  }
                } catch {}
                map.setZoomAndCenter(17, here)
              })
            },
            () => {
              // 失败则保持默认中心
            },
            { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
          )

          // 持续监听实时位置，高精度模式
          amapStore.watchId = navigator.geolocation.watchPosition(
            (pos) => {
              const { latitude, longitude, accuracy } = pos.coords
              if (accuracy && accuracy > 100) return // 过滤低精度
              convertGpsToGcj(longitude, latitude).then((gcj) => {
                const lnglat: [number, number] = [gcj[0], gcj[1]]
                const path = (polyline.getPath?.() || []) as [number, number][]
                // 跳点过滤：与上个点距离过大则忽略
                const last = path.length ? path[path.length - 1] as [number, number] : null
                if (last) {
                  const jump = calcDistance(last[1], last[0], lnglat[1], lnglat[0])
                  if (jump > 200) return
                  // 简单平滑：向上个点靠拢
                  lnglat[0] = last[0] * 0.3 + lnglat[0] * 0.7
                  lnglat[1] = last[1] * 0.3 + lnglat[1] * 0.7
                }
                path.push(lnglat)
                polyline.setPath(path as any)
                marker.setCenter(lnglat)

                // 回调位置更新（用 GCJ 坐标）
                if (onLocationUpdate) {
                  onLocationUpdate(lnglat[1], lnglat[0])
                }

                try {
                  if (!amapStore.accuracyCircle) {
                    amapStore.accuracyCircle = new AMap.Circle({ center: lnglat, radius: accuracy || 0 })
                    map.add(amapStore.accuracyCircle)
                  } else {
                    amapStore.accuracyCircle.setCenter(lnglat)
                    if (accuracy) amapStore.accuracyCircle.setRadius(accuracy)
                  }
                } catch {}
                map.setZoomAndCenter(17, lnglat)
              })
            },
            (err) => {
              console.warn('定位失败:', err.message)
            },
            { enableHighAccuracy: true, maximumAge: 0, timeout: 20000 }
          )
        }
      })
      .catch((e) => {
        console.error('地图加载失败:', e)
        setMapError(e.message || '地图加载失败')
      })

    return () => {
      disposed = true
      if (amapStore.watchId !== null) {
        navigator.geolocation.clearWatch(amapStore.watchId)
        amapStore.watchId = null
      }
      if (amapStore.map) {
        amapStore.map.destroy()
        amapStore.map = null
        amapStore.polyline = null
        amapStore.marker = null
      }
    }
  }, [keyStr])

  return (
    <div ref={containerRef} style={{ width: '100%', height: '100%', position: 'relative' }}>
      {mapError && (
        <div style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          background: 'rgba(0,0,0,0.8)',
          color: 'white',
          padding: '20px',
          borderRadius: '8px',
          textAlign: 'center',
          zIndex: 1000
        }}>
          <div style={{ marginBottom: '10px' }}>⚠️ 地图加载失败</div>
          <div style={{ fontSize: '14px', marginBottom: '15px' }}>{mapError}</div>
          <div style={{ fontSize: '12px', color: '#ccc' }}>
            请检查网络连接或联系管理员配置API Key
          </div>
        </div>
      )}
    </div>
  )
}

const AMapButtons: React.FC = () => {
  const show3DHere = () => {
    if (amapStore.map && amapStore.marker) {
      const c = amapStore.marker.getCenter?.() || defaultCenter
      try { amapStore.map.setStatus({ pitchEnable: true, rotateEnable: true }) } catch {}
      try { amapStore.map.setPitch(55) } catch {}
      try { amapStore.map.setRotation(0) } catch {}
      amapStore.map.setZoomAndCenter(18, c)
    }
  }
  const locateMe = () => {
    // 优先使用当前标记点；若无，则主动请求设备定位
    if (amapStore.map && amapStore.marker) {
      const c = amapStore.marker.getCenter?.()
      if (c) {
        try { amapStore.map.setPitch(0) } catch {}
        try { amapStore.map.setStatus({ pitchEnable: false, rotateEnable: false }) } catch {}
        try { if (amapStore.buildings) amapStore.map.remove(amapStore.buildings) } catch {}
        amapStore.map.setZoomAndCenter(17, c)
        return
      }
    }
    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition(
        (pos) => {
          const { latitude, longitude, accuracy } = pos.coords
          const AMapAny: any = (window as any).AMap
          const useCenter = (lng: number, lat: number) => {
            const here: [number, number] = [lng, lat]
            if (amapStore.marker) amapStore.marker.setCenter(here)
            if (amapStore.map) {
              try { amapStore.map.setPitch(0) } catch {}
              try { amapStore.map.setStatus({ pitchEnable: false, rotateEnable: false }) } catch {}
              try { if (amapStore.buildings) amapStore.map.remove(amapStore.buildings) } catch {}
              amapStore.map.setZoomAndCenter(17, here)
            }
            try {
              if (!amapStore.accuracyCircle && AMapAny) {
                amapStore.accuracyCircle = new AMapAny.Circle({ center: here, radius: accuracy || 0 })
                amapStore.map?.add(amapStore.accuracyCircle)
              } else {
                amapStore.accuracyCircle?.setCenter(here)
                if (accuracy) amapStore.accuracyCircle?.setRadius(accuracy)
              }
            } catch {}
          }
          try {
            if (AMapAny?.convertFrom) {
              AMapAny.convertFrom([longitude, latitude], 'gps', (status: string, result: any) => {
                if (status === 'complete' && result?.locations?.length) {
                  const loc = result.locations[0]
                  useCenter(loc.lng, loc.lat)
                } else {
                  useCenter(longitude, latitude)
                }
              })
            } else {
              useCenter(longitude, latitude)
            }
          } catch {
            useCenter(longitude, latitude)
          }
        },
        () => {},
        { enableHighAccuracy: true, timeout: 12000, maximumAge: 0 }
      )
    }
  }
  return (
    <>
      <button className="map-center2" onClick={show3DHere}>▶</button>
      <button className="map-locate" onClick={locateMe}>◎</button>
    </>
  )
}


